import {callApi} from '../../util/callApi';

/**
 * 获取用户列表
 * @returns {function()}
 */
const getList = (formdata) => {
  return (dispatch) => {
    const request_url = '/admin/user/list?page='+formdata.page;
    return callApi.get(request_url).then(res=>{
      if(res.code === 0){
        return Promise.resolve(dispatch({
          type: 'USER_LIST',
          pagination : res.data.pagination,
          userlist : res.data.results
        }))
      }else{
        return Promise.reject(res)
      }
    });
  }
}

/**
 * 添加用户
 * @param formdata
 * @returns {function()}
 */
const postAddUser = (formdata) => {
  return (dispatch) => {
    const request_url = '/admin/user/add';
    return callApi.post(request_url,JSON.stringify(formdata)).then(res=>{
      if(res.code === 0){
        return Promise.resolve(dispatch({
          type : 'USER_ADD',
          info : res.data
        }));
      }else{
        return Promise.reject(res)
      }
    });
  }
}

/**
 * 编辑用户信息
 * @param formdata
 * @returns {function()}
 */
const postEditUser = (formdata) => {
  return (dispatch) => {
    const request_url = '/admin/user/update';
    return callApi.post(request_url,JSON.stringify(formdata)).then(res=>{
      if(res.code === 0){
        return Promise.resolve(dispatch({
          type : 'USER_EDIT',
          index : formdata.index,
          info : res.data
        }));
      }else{
        return Promise.reject(res)
      }
    });
  }
}

/**
 * 删除用户信息
 * @param formdata
 * @returns {function()}
 */
const postDeleteUser = (formdata) => {
  return (dispatch) => {
    const request_url = '/admin/user/delete';
    return callApi.post(request_url,JSON.stringify(formdata)).then(res=>{
      return Promise.resolve(dispatch({
        type : 'USER_DELETE',
        index : formdata.index
      }));
    });

  }
}

/**
 * 冻结/解冻,用户
 * @param formdata
 * @returns {function()}
 */
const postFrozeUser = (formdata) => {
  return (dispatch) => {
    const request_url = '/admin/user/froze';
    return callApi.post(request_url,JSON.stringify(formdata)).then(res=>{
      return Promise.resolve(dispatch({
        type : 'USER_EDIT',
        index : formdata.index,
        info : res.data
      }));
    });
  }
}

export default {
  getList,
  postAddUser,
  postEditUser,
  postDeleteUser,
  postFrozeUser
}